package com.nowcoder.community.service;

import com.nowcoder.community.util.RedisKeyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SessionCallback;
import org.springframework.stereotype.Service;

@Service
public class LikeService {
    @Autowired
    private RedisTemplate redisTemplate;

    //点赞方法
    public void like(int userId,int entityType,int entityId,int entityUserId){
/*//通过工具获取相应的点赞key
        String entityLikeKey = RedisKeyUtil.getEntityLikeKey(entityType,entityId);
//判断用户是否已点赞，点一次点赞，两次取消
        Boolean isMember = redisTemplate.opsForSet().isMember(entityLikeKey, userId);
        if (isMember){
            redisTemplate.opsForSet().remove(entityLikeKey,userId);
        }else{
            redisTemplate.opsForSet().add(entityLikeKey,userId);
        }*/
        //启用事务管理
        redisTemplate.execute(new SessionCallback() {
            @Override
            public Object execute(RedisOperations operations) throws DataAccessException {
                String entityLikeKey = RedisKeyUtil.getEntityLikeKey(entityType,entityId);
                String userLikeKey= RedisKeyUtil.getUserLikeKey(entityUserId);

                Boolean isMemeber = operations.opsForSet().isMember(entityLikeKey, userId);
                operations.multi();
                if (isMemeber){
                    operations.opsForSet().remove(entityLikeKey,userId);
                    operations.opsForValue().decrement(userLikeKey);
                }else {
                    operations.opsForSet().add(entityLikeKey,userId);
                    operations.opsForValue().increment(userLikeKey);
                }
                return operations.exec();
            }
        });
    }

    // 查询某实体点赞的数量
    public long findEntityLikeCount(int entityType,int entityId){
        String entityLikeKey = RedisKeyUtil.getEntityLikeKey(entityType,entityId);
        return redisTemplate.opsForSet().size(entityLikeKey);
    }

    //查询某用户对某实体的点赞状态 就是看用户id是否在sets中
    // 返回整数 方便扩展实现更多评论形式 0 未点赞 1 点赞
    public int findEntityLikeStatus(int userId,int entityType,int entityId){
        String entityLikeKey = RedisKeyUtil.getEntityLikeKey(entityType,entityId);
        return redisTemplate.opsForSet().isMember(entityLikeKey, userId) ? 1 : 0;
    }

    //查询某用户获得的赞
    public int findUserLikeCount(int userId){
        String userLikeKey= RedisKeyUtil.getUserLikeKey(userId);
        return redisTemplate.opsForValue().get(userLikeKey) == null ?
                0 : (int)redisTemplate.opsForValue().get(userLikeKey);
    }
}
